package com.wzk.travelspringboot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzk.travelspringboot.dao.ScenicCommentDAO;
import com.wzk.travelspringboot.dao.ScenicCommentLikeDAO;
import com.wzk.travelspringboot.dao.UserDAO;
import com.wzk.travelspringboot.dto.LikedDTO;
import com.wzk.travelspringboot.dto.Result;
import com.wzk.travelspringboot.entity.ScenicComment;
import com.wzk.travelspringboot.entity.ScenicCommentLike;
import com.wzk.travelspringboot.entity.User;
import com.wzk.travelspringboot.service.ScenicCommentLikeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @Author: WangZiKang
 * @Date: 2025/1/13 20:34
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ScenicCommentLikeServiceImpl extends ServiceImpl<ScenicCommentLikeDAO, ScenicCommentLike> implements ScenicCommentLikeService {

    private final ScenicCommentLikeDAO likeDAO;

    private final UserDAO userDAO;

    private final ScenicCommentDAO commentDAO;

    @Override
    @Transactional
    public Result liked(LikedDTO dto) {
        //1.判断用户是否存在
        User user = userDAO.selectById(dto.getUserId());
        if (user == null || user.getState() != 1){
            return Result.failed("用户不存在或状态异常");
        }
        //2.判断评论是否存在
        int i = commentDAO.queryCommentCountById(dto.getCommentId());
        if (i <= 0){
            return Result.failed("该评论已经删除了");
        }
        //3.保存点赞数据
        ScenicCommentLike like = new ScenicCommentLike();
        like.setCommentId(dto.getCommentId());
        like.setUserId(dto.getUserId());
        like.setCreateTime(LocalDateTime.now());
        like.setUpdateTime(LocalDateTime.now());
        boolean b = save(like);
        if (!b){
            return Result.failed("出现未知错误！请联系管理员");
        }
        //4.评论点赞数+1
        int j = commentDAO.likeIncr(dto.getCommentId());
        if (j <= 0){
            return Result.failed("出现未知错误！请联系管理员");
        }
        return Result.success("点赞成功！",null);
    }

    @Override
    @Transactional
    public Result unlike(LikedDTO dto) {
        //1.取消点赞
        int i = likeDAO.removeLiked(dto.getCommentId(), dto.getUserId());
        if (i <= 0){
            return Result.failed("取消失败！请重试");
        }
        int j = commentDAO.likeDecr(dto.getCommentId());
        if (j <= 0){
            return Result.failed("出现未知错误！请联系管理员");
        }
        return Result.success("取消点赞成功！",null);
    }
}
